package cn.linlane.controller.sys;

import cn.linlane.controller.BaseController;
import cn.linlane.entity.errors.MyError;
import cn.linlane.entity.exception.MyException;
import cn.linlane.entity.sys.SysAuth;
import cn.linlane.entity.sys.SysUser;
import cn.linlane.service.sys.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@Api(value = "登录接口说明", description = "登录接口说明")
@RestController
@RequestMapping(value = "/sys")
public class LoginController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation(value = "用户登录", httpMethod = "POST", notes = "用户登录", response = SysAuth.class)
    @PostMapping("/login")
    public Object post(@RequestParam String username,
                       @RequestParam String password){
        SecurityUtils.getSubject().login(new UsernamePasswordToken(username, new Md5Hash(password, salt, hashIterations).toString()));
        return setSuccessMyMap(null);
    }

    @ApiOperation(value = "用户注销", httpMethod = "GET", notes = "用户注销", response = SysAuth.class)
    @GetMapping("/logout")
    public Object logOut(){
        SecurityUtils.getSubject().logout();
        return setSuccessMyMap(null);
    }

    @ApiOperation(value = "用户注册", httpMethod = "POST", notes = "用户注册", response = SysUser.class)
    @PostMapping("/register")
    public Object register(@RequestBody SysUser sysUser){
        if (!StringUtils.isEmpty(sysUser.getAccount()) && !StringUtils.isEmpty(sysUser.getPassword())){
            if (!sysUserService.existByAccount(sysUser.getAccount())){
                sysUser.setPassword(new Md5Hash(sysUser.getPassword(), salt, hashIterations).toString());
                return setSuccessMyMap(sysUserService.add(sysUser));
            }else {
                throw new MyException(MyError.USER_EXISTS);
            }
        }else {
            throw new MyException(MyError.PARAM_CANT_BE_NULL);
        }
    }


}
